package com.longteng.lesson.controller;

import com.longteng.lesson.po.MyUser;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by Administrator
 * DATE : 2018/5/20
 * TIME : 16:34
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Controller
@SessionAttributes(value = {"loginUser"})
public class LoginSystemController {
    @RequestMapping("/checkParamPage")
    public String checkParamPage() {
        return "/jsr/checkParamPage";
    }

    @RequestMapping("/loginSystem")
    public ModelAndView loginSystem(@Valid MyUser user, BindingResult bindingResult, HttpServletRequest request,HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        if (bindingResult.hasErrors()) {
            Field[] declaredFields = user.getClass().getDeclaredFields();
            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            for (Field field : declaredFields) {
                String fieldName = field.getName();
                boolean find = false;
                for (FieldError fieldError : fieldErrorList) {
                    String fieldErrorName = fieldError.getField();
                    if (fieldName.equalsIgnoreCase(fieldErrorName)) {
                        find = true;
                        modelAndView.addObject("errorMsg", fieldError.getDefaultMessage());
                        break;
                    }
                }
                if (find) {
                    break;
                }
            }
            modelAndView.setViewName("/jsr/checkParamPage");
            return modelAndView;
        }
        //密码不正确这种，属于你的业务逻辑校验，基础数据类型校验是做不到的
        String password = "aaaaaaaaa";
        //serivce dao
        //db 根据用户名唯一，查询出来这个用户，校验用户是否存在，如果存在的话，校验密码是否
        //数据肯定要放在一个地方，数据库，就是做持久化的。 登录
        String pagePassword = user.getPassword();
        if (!pagePassword.equalsIgnoreCase(password)) {
            bindingResult.rejectValue("password", "", "您输入的密码不正确!");
//            modelAndView.addObject("errorMsg", "您输入的密码不正确!");
            modelAndView.setViewName("/jsr/checkParamPage");
            return modelAndView;
        }
        modelAndView.setViewName("login/loginSuccess");
        modelAndView.addObject("loginUser", user);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (null != name && name.equalsIgnoreCase("JSESSIONID")) {
                cookie.setMaxAge(1000);
                cookie.setDomain("127.0.0.1");
                cookie.setPath("/");
                response.addCookie(cookie); //chrome://settings/content
                //http://127.0.0.1:8080/getUser
            }
        }
        return modelAndView;

    }

    @RequestMapping("/loginout")
    public ModelAndView loginout(SessionStatus status) {
        /**
         *   session的两种设置方式
         *   1.request.getSession().setAttribute("loginUser",user);
         *      这种session是放在request上的
         *      通过request去设置session
         *      取消用户登录方式
         *         httpSession.removeAttribute("loginUser");
         *         httpSession.invalidate();
         *  2.@SessionAttributes(value = {"loginUser"})
         *      这种session是放在SessionAttributesHandler上的
         *      取消用户登录方式
         *      SessionStatus status， status.setComplete()
         *     所以我们用的SessionAttributes，要用status.setComplete() 清除session
         *
         *    上面两个session分别放在两个不同的对象里面，所以之前那样处理不行
         */
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/checkParamPage");
        status.setComplete();
        return modelAndView;
    }
}
